using System;
using System.Collections.Generic;
using System.Text;
using moDb_prototype.Core;
using System.Runtime.Serialization;
using System.Collections;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace moDb_prototype.Serialization
{
    public class HashTableBinarySerializer<T> : BinarySerializer<T>, IBinarySerializer<T> 
    {
        private IFormatter formatter;
        private Hashtable properties;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:HashTableBinarySerializer<T>;"/> class.
        /// This Serializer uses an HashTable to serialize the public properties of the ObjectToSerialize
        /// </summary>
        /// <param name="objectToSerialize">The object to serialize.</param>
        public HashTableBinarySerializer(T objectToSerialize) : base(objectToSerialize)
        {
            formatter = new BinaryFormatter();
            properties = new Hashtable();
        }

        #region IBinarySerializer Members

        /// <summary>
        /// Reads the serialized record from a BinaryReader.
        /// </summary>
        /// <param name="reader">The reader.</param>
        public override void Read(BinaryReader reader)
        {       
            properties = (Hashtable)formatter.Deserialize(reader.BaseStream);
            foreach (PropertyInfo prop in propertiesToSerialize())
            {
                prop.SetValue(objectToSerialize, properties[prop.Name], null);
            }
        }

        /// <summary>
        /// Writes the serialized record to a BinaryWriter.
        /// </summary>
        /// <param name="writer"></param>
        public override void Write(BinaryWriter writer)
        {
            foreach (PropertyInfo prop in propertiesToSerialize())
            {
                properties.Add(prop.Name, prop.GetValue(objectToSerialize, null));
            }
            formatter.Serialize(writer.BaseStream, properties);
        }        
        #endregion        
    }
}